﻿package igz.fleaxy.util
{
	/**
	 * ...
	 * @author Intelygenz [www.intelygenz.com]
	 */
	public class Convert {
		public function Convert() {		}

		
		/**
		 *  Convierte un objeto a Booleano
		 * 
		 * @param	p_value Objeto a covertir
		 * @return  Booleano
		 * 
		 * @example valor = Convert.ToBoolean(variable);
		 */
		static public function $ToBoolean(p_value:Object) : Boolean {
			if ( p_value == null || !p_value || p_value == 0 || p_value == "" || p_value == "false" ) {
				return false;
			}
			else {
				return true;
			}
		}

		/**
		 *  Convierte un objeto a String
		 * 
		 * @param	p_value Objeto a covertir
		 * @return  String
		 * 
		 * @example cadena = Convert.ToString(variable);
		 */
		static public function $ToString(p_value:Object) : String {
			if ( p_value == null ) p_value = "";
			return p_value.toString();
		}

		/**
		 *  Convierte un objeto a Number
		 * 
		 * @param	p_value Objeto a covertir
		 * @return  Number
		 * 
		 * @example cadena = Convert.ToNumber(variable);
		 */
		static public function $ToNumber(p_value:*) : Number {
			if ( p_value == null ) p_value = 0;
			if ( isNaN(p_value) ) p_value = 0;
			return new Number( p_value );
		}
		
		/**
		 *  Convierte un objeto a Date
		 * 
		 * @param	p_value Objeto a covertir
		 * @return  Date
		 * 
		 * @example fecha = Convert.ToDate(variable);
		 */
		static public function $ToDate(p_string:String):Date {
		
			var expReg:RegExp = /^(\d{1,2})\/(\d{1,2})\/(\d{2}|(19|20)\d{2})$/;

			var result:Array = expReg.exec( p_string );
			
			if ( result == null ) {
				return null;
			  }
			  
			var month:int = parseInt( result[1] );
			var day:int = parseInt( result[2] );
		    var year:int = parseInt( result[3] );
			  
			if ( month > 12 || day > 31 || month == 0 || day == 0 ) {
				return null;
			} else if ( day == 31 && ( month == 9 || month == 4 || month == 6 || month == 11 || month == 2 ) ) {
				return null;
			} else if ( day == 30 && month == 2 ) {
				return null;
			} else if ( day == 29 && month == 2 && !( year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 ) ) ) {
				return null;
			} else {
				if ( year <= 15 ) {
				  year += 2000;    
				}

				return new Date( year, month - 1, day );
			}
		}

	}
	
}